
package org.jetnuke.modules.pictures;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.entities.Picture;

public class GetMediumPicture implements IAction {
	int pid;
	public void setPid(int pid) {
		this.pid = pid;
	}
	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		
		Picture picture=DataAccessDriver.getInst().newPictureDAO().retrieveByPK(pid);
		ByteArrayOutputStream baos=new ByteArrayOutputStream();
		
		String initPath=SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/pictures/"+picture.getUID()+"/";
		//String path = sc.getRealPath(initPath);
		File pathDir=new File(initPath);
		if(!pathDir.exists()){
			pathDir.mkdirs();
		}
		File f = null;
		
		if(picture.getMEDIUMNAME()!=null){
			
			f=new File(pathDir,picture.getMEDIUMNAME());
			response.setContentType(picture.getMEDIUMMIMETYPE());
			
		}else{
			f=new File(pathDir,picture.getFILENAME());
			response.setContentType(picture.getMIMETYPE());
		}
		BufferedInputStream bis=new BufferedInputStream(new FileInputStream(f));
		byte[] b = new byte[4096];
		
		while ((bis.read(b)) != -1) {
			baos.write(b);
		}
		bis.close();
		response.setContentLength(baos.size());
		OutputStream os=response.getOutputStream();
		baos.writeTo(os);
		return null;
	}

}
